### image combining coding by shenliwei

import os
from PIL import Image


def combine(img_list):
    widths = []
    heights = []
    for img in img_list:
        image1 = Image.open(img)
        widths.append(image1.size[0])
        heights.append(image1.size[1])

    w = max(widths)
    h = sum(heights)

    new_im = Image.new(mode='L', size=(w, h), color=255)

    for i in range(0, len(img_list)):
        image1 = Image.open(img_list[i])
        if i == 0:
            new_im.paste(image1, (0, 0))
        else:
            new_im.paste(image1, (0, sum(heights[0:i])))

    return new_im


path = '.'
file_list = os.listdir(path)
if 'subjects' in file_list:
    file_list.remove('subjects')
subject_list = {}
for item in file_list:
    x = item.find('_')
    if x == -1:
        subject_name = os.path.splitext(item)[0]
    else:
        subject_name = item[0:x]

    try:
        z = subject_name.index(".", subject_name.index(".") + 1)
        subject_name = subject_name[0:z]
    except:
        pass

    if subject_name[0:1] == 'a' or subject_name[0:1] == 'q':
        subject_name = subject_name[1:]

    if subject_name not in subject_list.keys():
        subject_list[subject_name] = [item]
    else:
        subject_list[subject_name] += [item]

# 排序
for subject in subject_list.keys():
    subject_list[subject] = sorted(subject_list[subject])
    i = 0
    for j in subject_list[subject]:
        if 'a' in j:
            i += 1
    a = subject_list[subject][0:i]
    q = subject_list[subject][i:]
    a = sorted(a, key=lambda qa: len(qa))
    q = sorted(q, key=lambda qa: len(qa))
    if len(subject) > 5:
        a = sorted(a, key=lambda qa: qa[7])
        q = sorted(q, key=lambda qa: qa[7])

    subject_list[subject] = q + a

# 合并题目与答案
save_path = 'd:/线性代数-学习辅导与习题解答-理工类-第4版-简明版'
folder = os.path.exists(save_path)
if not folder:  # 判断是否存在文件夹如果不存在则创建为文件夹
    os.makedirs(save_path)

for subject in subject_list:
    new_im = combine(subject_list[subject])
    new_im.save(os.path.join(save_path, subject + '.png'))

# path='.'
# file_list=set(os.listdir(path))
# lst=[]
# for f in file_list:
#     if f[0]=='a':
#         continue
# ##---process question part first
#     x=f.find('_')
#     y=f.rfind('.')
#     if x==-1:
#         tt=f
#     else:
#         tt=f[0:x]+f[y:]
#     if tt in file_list:
#         lst.append(tt)
#         file_list.remove(tt)

#     if x!=-1:
#         str1 = f[0:x] + f[x + 2:]
#         if os.path.exists(str1):
#             continue  ###file has been processed
#         f1=f[0:x]+'_1' + f[x + 2:]
#         f2=f[0:x]+'_2' + f[x + 2:]
#         if not os.path.exists(f1)  or not os.path.exists(f2):
#             print('数据出错啦！')
#             print(f1, '或者', f2, '未找到！')
#             continue

#         new_im = combine(f1, f2)
#         new_im.save(str1)
#         print('processed '+ f)


# #将所有下划线合起来（例如q1.1-1_1、q1.1-1_2合并成q1.1-1）
# path='.'
# file_list=os.listdir(path)
# subject_list={}
# for item in [name for name in file_list if ('_' in name)]:
#     x = item.find('_')
#     if x == -1:
#         print("文件名有误 " + str(item))
#         break 
#     if item[0:1] == 'a' or item[0:1] == 'q':
#         subject_name = item[1:x]
#     else:
#         subject_name = item[0:x]
#     if subject_name not in subject_list.keys():
#         subject_list[subject_name] = [item]
#     else:
#         subject_list[subject_name] += [item]

# #同一题之间排序
# for subject in subject_list.keys():
#     subject_list[subject] = sorted(subject_list[subject],key = lambda qa:qa[0])

# #合并答案或者题目的各个小块
# save_path = 'E:\bbb\'
# for subject in subject_list:
#     new_im = combine(subject_list[subject])
#     new_im.save(save_path + subject+'.png')        

# #合并题目与答案